//
//  FaQiShenPiXuanChengYuanViewController.m
//  JuBoCRM
//
//  Created by iMac on 2024/3/15.
//  Copyright © 2024 iningKe. All rights reserved.
//

#import "FaQiShenPiXuanChengYuanViewController.h"
#import "ZiDingYiXuanChengYuanTableViewCell.h"
@interface FaQiShenPiXuanChengYuanViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate,UITextFieldDelegate>{
    int page;
    NSMutableArray *dataSource;
    
    NSString *currentIndex;
}
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomSapce;

@property (weak, nonatomic) IBOutlet UITextField *searchTextView;
@property (weak, nonatomic) IBOutlet TPKeyboardAvoidingTableView *mainTableView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topSpace;
@end

@implementation FaQiShenPiXuanChengYuanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.customNavBar.title = @"关联客户";
    _topSpace.constant = NavaBarHeight;
    _bottomSapce.constant = ScreenBottom+20;
    
    [_mainTableView registerNib:[UINib nibWithNibName:@"ZiDingYiXuanChengYuanTableViewCell" bundle:nil] forCellReuseIdentifier:@"ZiDingYiXuanChengYuanTableViewCell"];
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self downRefresh];
    }];

    _mainTableView.mj_header = header;
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self upRefresh];
    }];
    _mainTableView.mj_footer = footer;
    page = 1;
    [self getInfoFromServer];
    
    
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    [self downRefresh];
    return YES;
}

//上拉刷新
- (void)upRefresh {
    page++;
    [self getInfoFromServer];
}

//下拉刷新
- (void)downRefresh {
    page = 1;
    [self getInfoFromServer];
}

- (void)getInfoFromServer{
    
    NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
    [paraDic setValue:[NSString stringWithFormat:@"%d",page] forKey:@"page"];
    [paraDic setValue:@10 forKey:@"limit"];
    [paraDic setValue:_searchTextView.text forKey:@"search"];
    [paraDic setValue:@"2" forKey:@"type"];
    NSString *url = @"/crmCustomer/queryPageList";
    [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:url andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if (!error) {
            NSLog(@"info:%@",info);
            NSArray *array = [[info objectForKey:@"data"] objectForKey:@"list"];
            if (page == 1) {
                if ([array count]> 9) {
                    dataSource = [NSMutableArray arrayWithArray:array];
                    [_mainTableView.mj_header endRefreshing];
                    [_mainTableView.mj_footer endRefreshing];
                }else {
                    dataSource = [NSMutableArray arrayWithArray:array];
                    [_mainTableView.mj_header endRefreshing];
                    [_mainTableView.mj_footer endRefreshingWithNoMoreData];
                    if(dataSource.count == 0){
                        _mainTableView.mj_footer.hidden = YES;
                    }else{
                        _mainTableView.mj_footer.hidden = NO;
                    }
                }
            }else {
                if ([array count]> 9) {
                    [dataSource addObjectsFromArray:array];
                    [_mainTableView.mj_header endRefreshing];
                    [_mainTableView.mj_footer endRefreshing];
                }else {
                    NSArray *tempArray = array;
                    if (tempArray.count > 0) {
                        [dataSource addObjectsFromArray:tempArray];
                    }
                    [_mainTableView.mj_header endRefreshing];
                    [_mainTableView.mj_footer endRefreshingWithNoMoreData];
                }
            }
            
            [_mainTableView reloadData];
            
            
        }else {
            [_mainTableView.mj_header endRefreshing];
            [_mainTableView.mj_footer endRefreshing];
        }
    }];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    ZiDingYiXuanChengYuanTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZiDingYiXuanChengYuanTableViewCell"];
    NSDictionary *dataDic = dataSource[indexPath.row];
    NSString *result = [NSString stringWithFormat:@"%@  %@",GetHandleString(dataDic, @"customerName"),GetHandleString(dataDic, @"mobile")];
    if(_isFromGenJin && currentIndex.length > 0 &&  currentIndex.integerValue == indexPath.row){
        cell.selectButton.selected = YES;
    }else{
        cell.selectButton.selected = [GetHandleString(dataDic, @"selected") boolValue];
    }
    cell.selectButton.userInteractionEnabled = NO;
    cell.rightButton.hidden = YES;
    
    if(_searchTextView.text.length > 0){
        cell.nameLabel.text = nil;
        cell.nameLabel.attributedText = [self stringWithParHighSubString:result andSubString:_searchTextView.text];
    }else{
        cell.nameLabel.attributedText = nil;
        cell.nameLabel.text = result;
    }
    
    return cell;
}

- (NSMutableAttributedString *)stringWithParHighSubString:(NSString *)string andSubString:(NSString *)subString{
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:string];
    NSString *copyTotalString = string;
    NSMutableString *replaceString = [NSMutableString  stringWithString:@" "];
    for (int i = 0; i < subString.length; i++) {
        NSString *singleString = [subString substringWithRange:NSMakeRange(i, 1)];
        while ([copyTotalString rangeOfString:singleString].location != NSNotFound) {
            NSRange range = [copyTotalString rangeOfString:singleString];
            [attributeString addAttribute:NSForegroundColorAttributeName value:rgba(59, 97, 255, 1) range:range];
            copyTotalString = [copyTotalString stringByReplacingCharactersInRange:range withString:replaceString];
        }
    }
    return attributeString;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSMutableDictionary *dataDic = [NSMutableDictionary dictionaryWithDictionary:dataSource[indexPath.row]];
    
    if(_isFromGenJin){
        currentIndex = [NSString stringWithFormat:@"%ld",indexPath.row];
    }else{
        [dataDic setValue:[NSString stringWithFormat:@"%d",![GetHandleString(dataDic, @"selected") boolValue]] forKey:@"selected"];
        [dataSource replaceObjectAtIndex:indexPath.row withObject:dataDic];
    }
    [_mainTableView reloadData];
}

//确定
- (IBAction)queDing:(UIButton *)sender {
    NSMutableString *name = [NSMutableString string];
    NSMutableString *idString = [NSMutableString string];
    if (_isFromGenJin) {
        if(currentIndex.length == 0){
            [ZZPUtils showWarning:@"请先选择成员"];
            return;
        }
        NSDictionary *dataDic = dataSource[[currentIndex integerValue]];
        name = [NSMutableString stringWithString:GetHandleString(dataDic, @"customerName")];
        idString = [NSMutableString stringWithString:GetHandleString(dataDic, @"customerId")];
     
        NSString *nameResult = name;
        NSString *idResult = idString;
   
        if(_manageClickResultBlock){
            _manageClickResultBlock(nameResult,idResult);
        }
    }else{
        for (NSDictionary *dataDic in dataSource) {
            if ([GetHandleString(dataDic, @"selected") boolValue]) {
                [name appendString:[NSString stringWithFormat:@"%@,",GetHandleString(dataDic, @"customerName")]];
                [idString appendString:[NSString stringWithFormat:@"%@,",GetHandleString(dataDic, @"customerId")]];
            }
        }
        if(idString.length == 0){
            [ZZPUtils showWarning:@"请先选择成员"];
            return;
        }
        NSString *nameResult = name;
        NSString *idResult = idString;
        if(idString.length > 0){
            idResult = [idString substringToIndex:idString.length-1];
        }
        if(name.length > 0){
            nameResult = [name substringToIndex:name.length-1];
        }
        
        if(_manageClickResultBlock){
            _manageClickResultBlock(nameResult,idResult);
        }
    }

 
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView{
    return -90;
}

-(UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamed:@"暂无搜索"];
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"暂无数据~"attributes: @{NSFontAttributeName: [UIFont systemFontOfSize:16],NSForegroundColorAttributeName: rgba(163, 168, 185, 1)}];
    return string;
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    return YES;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end





